package config

import (
	"encoding/json"
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Config struct {
	// Mysql *Mysql `toml:"mysql"`
	Mysql *Mysql
	Api   *Api
}

func (c *Config) String() string {
	js, _ := json.Marshal(c)
	return string(js)
}

func DefaultConfig() *Config {
	return &Config{
		Mysql: &Mysql{
			Address:  "localhost",
			Port:     3307,
			Username: "vblog",
			Password: "123456",
			Database: "vblog",
		},
		Api: &Api{
			Apiadress: "127.0.0.1",
			Apiport:   8090,
		},
	}
}

type Mysql struct {
	Address  string `json:"address" toml:"address"`
	Port     int    `json:"port" toml:"port" env:"port"`
	Username string `json:"username" toml:"username"`
	Password string `json:"password" toml:"password"`
	Database string `json:"database" toml:"database"`
}

type Api struct {
	Apiadress string
	Apiport   int
}

// 连接数据库：dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
// db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
func (m *Mysql) DNS() string {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		m.Username, m.Password, m.Address, m.Port, m.Database)
	return dsn
}

func (m *Mysql) Getconn() *gorm.DB {
	db, _ := gorm.Open(mysql.Open(m.DNS()), &gorm.Config{})
	// if err != nil {
	// 	return nil, err
	// }
	// return db, nil
	return db
}
